package com.atguigu.flink.charkoer10;

import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.client.program.StreamContextEnvironment;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

public class FlinkBroadCoast {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamContextEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        DataStreamSource<String> data = env.socketTextStream("hadoop162", 8888);
        DataStreamSource<String> control = env.socketTextStream("hadoop162", 9999);

        // 1. 把控制流做成广播流
        MapStateDescriptor<String, String> bcStateDec = new MapStateDescriptor<>("bcState", String.class, String.class);
        BroadcastStream<String> broadcast = control.broadcast(bcStateDec);

        // 2. 让数据流connect 广播流
        BroadcastConnectedStream<String, String> connectedStream = data.connect(broadcast);

        connectedStream.process(new BroadcastProcessFunction<String, String, String>() {
            @Override
            public void processElement(String value, ReadOnlyContext ctx, Collector<String> out) throws Exception {

                // 4. 数据流中数据, 从广播状态读取配置信息
                ReadOnlyBroadcastState<String, String> readOnlyBroadcastState = ctx.getBroadcastState(bcStateDec);
                String a1 = readOnlyBroadcastState.get("a1");

                if ("1".equals(a1)) {
                    out.collect("切换到1号处理逻辑");
                } else if ("2".equals(a1)) {
                    out.collect("切换到2号处理逻辑");
                } else {
                    out.collect("默认处理逻辑");
                }
            }

            // 处理广播流中的元素
            @Override
            public void processBroadcastElement(String value, Context ctx, Collector<String> out) throws Exception {
                // 3. 把配置信息放入广播状态
                BroadcastState<String, String> broadcastState = ctx.getBroadcastState(bcStateDec);

                broadcastState.put("a1", value);
            }
        }).print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
